# -*- coding = utf-8 -*-
# @Time : 2023/5/19 13:18
# @Author :Henry L
# @File : LN.py
import glob
import os
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


class LN:
    def __init__(self):
        options = webdriver.ChromeOptions()
        self.host = "http://ggzy.ln.gov.cn/"
        prefs = {"plugins.always_open_pdf_externally": True,
                 "download.default_directory": os.getcwd() + "\\"}
        options.add_experimental_option("prefs", prefs)
        self.url = ['http://ggzy.ln.gov.cn/yphc/tzgg/yp/', 'http://ggzy.ln.gov.cn/yphc/tzgg/hc/', 'http://ggzy.ln.gov.cn/yphc/tzgg/ym/']
        self.driver = webdriver.Chrome(options=options)
        self.driver.maximize_window()
        self.wait = WebDriverWait(driver=self.driver, timeout=10)
        self.driver.get(self.url[0])

    def get(self, page):
        time.sleep(3)
        lis = self.driver.find_elements(By.CLASS_NAME, "dh_lul")
        for i in range(1, len(lis)):
            if i > 0:
                url = self.url[i]
            lis = self.driver.find_elements(By.CLASS_NAME, "dh_lul")
            self.driver.execute_script("window.scroll(0,-1000)")
            lis[i].find_element(By.TAG_NAME, "a").click()
            time.sleep(2)
            lan = self.driver.find_elements(By.XPATH, "/html/body/div[1]/div[2]/div[2]/ul/li/a")
            dates = self.driver.find_elements(By.XPATH, "/html/body/div[1]/div[2]/div[2]/ul/li/span")
            for item in range(0, len(lan)):
                time.sleep(3)
                # if item.find_element(By.XPATH, "div[1]/div[2]").text == '公告标题':
                #     continue
                date = dates[item].get_attribute('innerText')
                lan[item].click()
                handles = self.driver.window_handles
                self.driver.switch_to.window(handles[-1])
                time.sleep(1.5)
                title = self.driver.find_element(By.CLASS_NAME, "dlist_title").get_attribute('innerText')
                box = self.driver.find_element(By.CLASS_NAME, "dlist_con")
                view_time = self.driver.find_element(By.CLASS_NAME, "viewsCount").get_attribute('innerText').split('：')[-1]
                content = box.get_attribute("outerHTML")
                attachments = box.find_elements(By.TAG_NAME, "a")
                attachments_list = []
                if len(attachments) > 0:
                    for attach in attachments:
                        if attach.get_attribute('innerText') == "" or attach.get_attribute('href') is None or "有采购记录的尚未入库医用耗材码外产品" in attach.get_attribute('innerText')\
                                or "附件1" == attach.get_attribute('innerText') or "附件2" == attach.get_attribute('innerText'):
                            continue
                        if "upload" in attach.get_attribute("href") or "UploadFile" in attach.get_attribute("href") \
                                or "附件" in attach.text:
                            self.driver.execute_script("window.scroll(0,1000)")
                            attach.click()
                            time.sleep(1)
                            # href = a.get_attribute("href").split('.')[0]
                            # a_name = href.split('/')[-1]
                            # attachments_list.append(a_name)
                            # self.get_last_filename_and_rename(os.getcwd(), a_name)
                time.sleep(1)
                while self.driver.current_url != url:
                    self.driver.close()
                    handles = self.driver.window_handles
                    self.driver.switch_to.window(handles[-1])
                    time.sleep(1)
                data_list = [title, date, view_time, content, attachments_list]
                print(data_list)

    def get_last_filename_and_rename(self, sav_folder, new_filename):
        files = glob.glob(sav_folder + '/*')
        max_file = max(files, key=os.path.getctime)
        filename = max_file.split("/")[-1].split(".")[0]
        new_path = max_file.replace(filename, new_filename)
        os.rename(max_file, new_path)
        return new_path

    def close(self):
        time.sleep(60)
        self.driver.quit()


ln = LN()
ln.get("")
ln.close()

